/* eslint-disable @typescript-eslint/no-unused-vars */
'use client';
import ClientLayout from '@/components/clientLayout';
import { MutableRefObject, useEffect, useRef, useState } from 'react';
import './index.scss';

const Page: React.FC = () => {
	const [arr, setArr] = useState([] as number[][]);
	const canRef: MutableRefObject<HTMLCanvasElement | undefined> = useRef();

	useEffect(() => {
		draw(arr, 'red', 4);
		calculate();
	}, [arr]);
	const calF = (point: number[], gs: unknown[], arr: number[][]) => {
		let y = 0;
		gs.forEach((item:any, i) => {
			
			const x = point[0];
			y += (eval(item.funzi) / item.fenmu) * arr[i][1];
		});
		return [point[0], y];
	};
	const calculate = () => {
		const gs: unknown[] = [];
		arr.forEach((item) => {
			gs.push(handleX(item));
		});
		const tmp: number[][] = [];
		arr.forEach((item) => {
			tmp.push(calF(item, gs, arr));
		});
		// tmp.push(calF([200, 250], gs));
		console.log(gs);

		draw(tmp, '#00f', 1, false);
	};

	const handleX = (point: number[]) => {
		let y = 1;
		let str = '';
		arr.forEach((item) => {
			if (item != point) {
				y *= point[0] - item[0];
				str += `(x-${item[0]})*`;
			}
		});
		return {
			fenmu: y,
			funzi: str + '1',
		};
	};
	// const clearCanvas = (ctx: CanvasRenderingContext2D) => {};

	const draw = (
		list: number[][],
		strokeColor = 'red',
		lineWidth = 1,
		isClear = true,
	) => {
		const canvas = canRef.current;
		if (canvas && arr.length) {
			const ctx = canvas.getContext('2d');
			if (ctx) {
				if (isClear) ctx.clearRect(0, 0, canvas.width, canvas.height);
				ctx.fillStyle = '#0f0';
				ctx.lineWidth = lineWidth;
				ctx.beginPath();
				ctx.moveTo(list[0][0], list[0][1]);
				ctx.strokeStyle = strokeColor;
				for (let i = 1; i < list.length; i++) {
					ctx.lineTo(list[i][0], list[i][1]);
				}
				ctx.stroke();
				for (let i = 0; i < list.length; i++) {
					ctx.beginPath();
					ctx.arc(list[i][0], list[i][1], 5, 0, 2 * Math.PI);
					ctx.fill();
				}
			}
		}
	};

	const handleClick = (e: MouseEvent) => {
		const rect = canRef.current?.getBoundingClientRect();
		if (rect) {
			const x = e.clientX - rect.left;
			const y = e.clientY - rect.top;
			setArr([...arr, [x, y]]);
		}
	};


	
	return (
		<ClientLayout>
			<div className="inter">
				<canvas
					ref={canRef}
					onClick={handleClick}
					width={900}
					height={600}
				></canvas>
			</div>
		</ClientLayout>
	);
};
export default Page;
